package com.ocelot.san.controller;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.icefaces.ace.model.table.LazyDataModel;
import org.icefaces.ace.model.table.SortCriteria;
import org.springframework.data.domain.Page;

import com.icesoft.faces.context.effects.JavascriptContext;
import com.ocelot.san.constants.ApplicationConstants;
import com.ocelot.san.dto.Operation;
import com.ocelot.san.service.OperationService;
import com.ocelot.san.utils.FacesUtils;

@ManagedBean
@ViewScoped
public class OperationUpdateController implements Serializable {
	
	private static final long serialVersionUID = -1032031981419404851L;

	private Long idToFetch;
	private Integer pageSize = ApplicationConstants.GLOBAL_PAGE_SIZE;
	private LazyDataModel<Operation> operations;
	
	@ManagedProperty(value = "#{operationService}")
	private OperationService operationService;
	
	
	@PostConstruct
	public void init() {
		JavascriptContext.includeLib("/js/util/ace-jquery.js", FacesContext.getCurrentInstance()); 
		operations = new LazyDataModel<Operation>() {
			
			private static final long serialVersionUID = 1L;
			
			Page<Operation> page;
			@Override
			public List<Operation> load(int startRow, int pageSize, 
											SortCriteria[] sort, Map<String, String> filter) {
				startRow++;
				int currentPage = (startRow <= pageSize)? 0 : startRow / pageSize;
	    		page = operationService.fetchAllOperationsWithPage(currentPage, pageSize, sort);
	    		setRowCount((int) page.getTotalElements());
	    		return page.getContent();
	    	}
			
			
		};
	}
	
	public String fetchOperation() {
		FacesUtils.getInstance().setManagedBeanInSession(ApplicationConstants.SELECTED_OPERATION_ID, getIdToFetch());
		return "operation";
	}
	
	
	public OperationService getOperationService() {
		return operationService;
	}

	public void setOperationService(OperationService operationService) {
		this.operationService = operationService;
	}

	public Long getIdToFetch() {
		return idToFetch;
	}

	public void setIdToFetch(Long idToFetch) {
		this.idToFetch = idToFetch;
	}
	
	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}
	
	
	public LazyDataModel<Operation> getOperations() {
		return operations;
	}

	public void setOperations(LazyDataModel<Operation> operations) {
		this.operations = operations;
	}

}
